package com.lagou.seckill.common.utils;


import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * 重试拦截器
 */
@Slf4j
public class RetryIntercepter implements Interceptor {
    //最大重试次数
    public int maxRetry;
    //假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
    private int retryNum = 0;

    private long interval = 1000;

    public RetryIntercepter(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    public RetryIntercepter(int maxRetry, Long interval) {
        this.maxRetry = maxRetry;
        if(interval!=null){
            this.interval = interval;
        }
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        boolean failed = false;
        Request request = chain.request();
        //log.info("retryNum=" + retryNum);
        Response response = null;
        try{
            response = chain.proceed(request);
        }catch (Exception e){
            failed = true;
            log.error("请求失败开始重试",e);
        }
        while ((failed || !response.isSuccessful()) && retryNum < maxRetry) {
            if(response!=null){
                log.error(response.toString());
            }
            retryNum++;
            log.info("retryNum=" + retryNum);
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try{
                if(response!=null){
                    response.close();
                }
                response = chain.proceed(request);
                failed = false;
            }catch (Exception e){
                failed = true;
                log.error("请求失败开始重试",e);
                if(retryNum<maxRetry){
                    throw e;
                }
            }
        }
        return response;
    }
}
